<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>WebGL Demo</title>
    <link rel="stylesheet" href="./webgl.css" type="text/css" />
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
      integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
      crossorigin="anonymous"
      defer
    ></script>
    <script src="webgl-demo.js" type="module" defer></script>
  </head>
  <body onload="main()">
    <canvas id="glcanvas" width="640" height="480">
      你的浏览器似乎不支持或者禁用了 HTML5
      <code>&lt;canvas&gt;</code>
      元素。
    </canvas>
  </body>
</html>
<script>
  // 从这里开始
  function main() {
    const canvas = document.querySelector('#glcanvas')
    // 初始化 WebGL 上下文
    const gl = canvas.getContext('webgl')

    // 确认 WebGL 支持性
    if (!gl) {
      alert('无法初始化 WebGL，你的浏览器、操作系统或硬件等可能不支持 WebGL。')
      return
    }

    // 使用完全不透明的黑色清除所有图像
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    // 用上面指定的颜色清除缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT)

    // Vertex shader program

    const vsSource = `
    attribute vec4 aVertexPosition;

    uniform mat4 uModelViewMatrix;
    uniform mat4 uProjectionMatrix;

    void main() {
      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
    }
  `
    const fsSource = `
    void main() {
      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
  `
    const shaderProgram = initShaderProgram(gl, vsSource, fsSource)
    const programInfo = {
      program: shaderProgram,
      attribLocations: {
        vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
      },
      uniformLocations: {
        projectionMatrix: gl.getUniformLocation(
          shaderProgram,
          'uProjectionMatrix',
        ),
        modelViewMatrix: gl.getUniformLocation(
          shaderProgram,
          'uModelViewMatrix',
        ),
      },
    }
    // Here's where we call the routine that builds all the
    // objects we'll be drawing.
    const buffers = initBuffers(gl)

    // Draw the scene
    drawScene(gl, programInfo, buffers)
  }
</script>
